﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SP = Microsoft.SharePoint.Client;

namespace com.sharepointutils.application.Forms
{
    public partial class UpdateForm : Form
    {
        private SharePointConnection ToConnection = new SharePointConnection();
        private SharePointConnection FromConnection = new SharePointConnection();

        public UpdateForm()
        {
            InitializeComponent();
        }

        private void button_selectTo_Click(object sender, EventArgs e)
        {

            FormUtilities.OpenListNode(((MainForm)this.MdiParent).SelectedNode,  ToConnection);

            lbl_update_to.Text = ToConnection.Label;

            if (ToConnection != null)
            {
                //listBox_fields2.DataSource = SharePointUtilities.getListColumns(ToConnection.URL, ToConnection.Credentials, ToConnection.List);
            }
        }

        private void button_selectFrom_Click(object sender, EventArgs e)
        {
            FormUtilities.OpenListNode(((MainForm)this.MdiParent).SelectedNode, FromConnection);
            lbl_update_from.Text = FromConnection.Label;

            if (FromConnection != null)
            {
                //listBox_fields1.DataSource = SharePointUtilities.getListColumns(FromConnection.URL, FromConnection.Credentials, FromConnection.List);
            }
        }

        private void btn_match_Click(object sender, EventArgs e)
        {
            //FieldDropdownChoice col1 = listBox_fields1.SelectedItem as FieldDropdownChoice;
            //FieldDropdownChoice col2 = listBox_fields2.SelectedItem as FieldDropdownChoice;
            //listBox_matches.Items.Add(new FieldMatch (col1, col2));
        }

        private void btn_updateList_Click(object sender, EventArgs e)
        {
            SP.ListItemCollection collection = SharePointUtilities.getAllListItems(FromConnection.URL, FromConnection.List, FromConnection.Credentials);

            foreach (SP.ListItem x in collection)
            {
                Dictionary<String, object> values = new Dictionary<string, object>();
                String name = x["FileLeafRef"].ToString();

                foreach (FieldMatch match in listBox_matches.Items)
                {
                    if (x[match.InternalName1] != null)
                    {
                        values.Add(match.InternalName2, x[match.InternalName1]);
                    }
                }
                SharePointUtilities.updateListItem(ToConnection.URL, ToConnection.Credentials, ToConnection.List, name, values);
            }
        }

        private void btn_copyListItems_Click(object sender, EventArgs e)
        {
            btn_copyListItems.Enabled = false;
            backgroundWorker_copy.RunWorkerAsync();
        }

        private void backgroundWorker_copy_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;

            SP.ListItemCollection collection;
            if(String.IsNullOrWhiteSpace(txt_query.Text))
            {
                collection = SharePointUtilities.getAllListItems(FromConnection.URL, FromConnection.List, FromConnection.Credentials);
            }
            else
            {
                collection = SharePointUtilities.getAllListItems(FromConnection.URL, FromConnection.List, txt_query.Text, FromConnection.Credentials);
            }

            int count = 0;

            SP.BaseType FromType = SharePointUtilities.GetListType(FromConnection.URL, FromConnection.Credentials, FromConnection.List);
            SP.BaseType ToType = SharePointUtilities.GetListType(ToConnection.URL, ToConnection.Credentials, ToConnection.List);

            if (FromType == ToType)
            {
                try
                {
                    foreach (SP.ListItem x in collection)
                    {
                        if (worker.CancellationPending == true)
                        {
                            e.Cancel = true;
                            break;
                        }
                        else
                        {
                            worker.ReportProgress((count / collection.Count) * 100);
                            Dictionary<String, object> values = new Dictionary<string, object>();
                            foreach (dynamic match in listBox_matches.Items)
                            {
                                if (x[match.InternalName1] != null)
                                {
                                    values.Add(match.InternalName2, x[match.InternalName1]);
                                }
                            }

                            if (FromType == SP.BaseType.DocumentLibrary)
                            {
                                using(System.IO.Stream stream = SharePointUtilities.DownloadListItem(FromConnection.URL, x))
                                {
                                    SharePointUtilities.uploadDocument(ToConnection.URL, ToConnection.Credentials, ToConnection.List, x["FileLeafRef"].ToString(), stream, values);
                                }
                            }
                            else
                            {
                                int newID = SharePointUtilities.createListItem(ToConnection.URL, ToConnection.List, values, ToConnection.Credentials);
                                try
                                {
                                    if (checkBox_includeAttachments.Checked)
                                    {
                                        SharePointUtilities.AttachFilesToListItem(ToConnection.URL, ToConnection.List, newID, ToConnection.Credentials, SharePointUtilities.DownloadAttachedFilesFromListItem(FromConnection.URL, FromConnection.List, x.Id, FromConnection.Credentials));
                                    }
                                }
                                catch (Exception wx)
                                {
                                    String efff = wx.Message;
                                }
                            }
                        }
                        count++;
                    }
                }
                catch (Exception ex)
                {
                    String eff = ex.Message;
                    //errorLog.Append("Failed to copy Items - Message: " + ex.Message);
                    //txt_errorLog.Text += Environment.NewLine + errorLog.ToString();
                }
            }
            else
            {
                throw new Exception("Base Types of lists do not match");
            }
        }

        private void backgroundWorker_copy_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progressBar_main.Value = e.ProgressPercentage;
        }

        private void backgroundWorker_copy_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            progressBar_main.Value = 100;
            btn_copyListItems.Enabled = true;
        }




    }

    public class FieldMatch
    {
        public String Title { get; set; }
        public String InternalName1 { get; set; }
        public String InternalName2 { get; set; }

        //public FieldMatch(FieldDropdownChoice col1, FieldDropdownChoice col2)
        //{
        //    Title = col1.Title + " - " + col2.Title; 
        //    InternalName1 = col1.InternalName;
        //    InternalName2 = col2.InternalName;
        //}
    }
}
